# _*_ coding: utf-8 _*_
# @Author   : Wei Yue
# @Time     : 2023-05-12 14:09
# @Function : 电机电感、磁链标定

import pandas as pd
import numpy as np
from scipy.interpolate import interp1d
from utils.MyInterpolate import MyInterpolate2D

def calculateKe():
    # 已知phi_d,id,iq,Ld,Lq,插值计算Ke 也就是phi_f
    path = '../excel/motorMap.xlsx'
    Id_table = pd.read_excel(path,sheet_name='Id',index_col=0)
    Iq_table = pd.read_excel(path,sheet_name='Iq',index_col=0)
    Fluxd_table = pd.read_excel(path,sheet_name='Flux_d',index_col=0)
    Ld_table = pd.read_excel(path,sheet_name='LdMap',index_col=0)
    x=Ld_table.index.values
    y=Ld_table.columns.values
    # 构建二维插值 查不同id iq下的Ld
    myInterpolate2D = MyInterpolate2D(x,y,Ld_table)
    # 遍历id iq的table
    row = Id_table.index.values
    columns = Id_table.columns.values
    outKePd = pd.DataFrame(columns=['id','iq','ke'])
    print(Id_table)
    print(Iq_table)
    print(Fluxd_table)
    print(Ld_table)
    for r in row:
        for col in columns:
            # 跳过0转速或者0转矩 （这部分数据是自己插值的 不准确）
            if r ==0 or col == 0:
                continue
            id = Id_table.loc[r,col]
            iq = Iq_table.loc[r,col]
            flux_d = Fluxd_table.loc[r,col]
            if pd.isna(id) or pd.isna(iq) or pd.isna(flux_d):
                continue
            Ld = myInterpolate2D.interp(id,iq)
            outKePd.loc[len(outKePd)]=[id,iq,flux_d-Ld*id]
    outKePd.to_excel('../excel/keMap.xls')


def transferToStandard(idMin, idMax, iqMin, iqMax, path):
    keMap = pd.read_excel(path)
    iq = keMap.loc[:,'iq'].values
    ke = keMap.loc[:,'ke'].values
    f1=interp1d(iq,ke)
    iqRange = np.arange(0,360,10)
    keRange = f1(iqRange)
    newPd = pd.DataFrame()
    newPd.loc[:,'iq'] = iqRange
    newPd.loc[:,'ke'] = keRange
    newPd.to_excel('../excel/newKe.xlsx')




if __name__ == '__main__':
    calculateKe()
    transferToStandard(-470, 0, 0, 350, '../excel/normalizedKe.xlsx')




